package com.lcf.app.security.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.List;

/**
 * @author ChenFei
 * @date 2021/11/18
 */
@Configuration
public class UserDetailsServiceImpl implements UserDetailsService {

    private static final String USERNAME = "admin";
    private static final String PASSWORD = new BCryptPasswordEncoder().encode("123456");

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        if (!USERNAME.equals(s)) {
            throw new UsernameNotFoundException("用户不存在");
        }
        //给用户设置权限和角色，角色必须以 'ROLE_' 开头
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList("user", "ROLE_USER");
        return new User(USERNAME, PASSWORD, authorityList);
    }
}
